/*
*	String Formatting Library
*	Written by Andrew Moore
*	Arctic Region Supercomputing Center (ARSC)
*	Created June 18, 2009
*	Last Revised October 15, 2009
*/

/*	Header Files		*/
#include "stringFormatting.h"
/*				*/
/*	Function Definitions	*/
std::string stringFormatCorrector (std::string correctThis, int place) // Format the input.
{
	std::string corrected = "\n";  // This is the string that will be sent back to the calling function for display.
	int ready = 0;  // Used to determine whether we are at usable information or not.
	int space = 0;   // Keeps track of the index of the last space in the string.
	int characters = 0;  // Keep track of the number of characters in the current line.
	int placeHolder = 0; // Variable to make sure the space detection is correct.

	for (unsigned int i = 0; i < correctThis.length(); i++)  // Loop through the string.
	{
		//osg::notify(osg::NOTICE) << "Space = " << space << std::endl;
		//osg::notify(osg::NOTICE) << "Ready = " << ready << std::endl;
		if (ready == 0)   //  Not at the usable portion yet.
		{
			if (correctThis[i] == ':')  //  The usable portion starts at the next character.
				ready++;
			else
				placeHolder++;
		}
		else if (ready == 1)  // Code for formatting the usable portion.
		{
			if (place >= 0)  // No problems, go ahead and get our data.
			{
				// Call the function to handle the trimming of the string as well as adding characters to our corrected string.
				i = trimString (correctThis,corrected,placeHolder,i,space,characters);

				/*if (characters == 0)
				{
					osg::notify(osg::NOTICE) << "Corrected:  " << corrected << std::endl;
					osg::notify(osg::NOTICE) << "i:  " << i << std::endl;
					osg::notify(osg::NOTICE) << "space:  " << space << std::endl;
					osg::notify(osg::NOTICE) << "characters:  " << characters << std::endl;
				}*/

				//osg::notify(osg::NOTICE) << "Title" << std::endl;
			}
				
			else  // Problem, place is not a valid number.
				osg::notify(osg::NOTICE) << "Something went terribly wrong." << std::endl;
		}
	}
	 
	//osg::notify(osg::NOTICE) << "The Corrected String is " << corrected << std::endl;

	return corrected;
}

int trimString (std::string input,std::string& temp, int offset, int index,int& space,int& characters)
{	
	if (characters < 85)
	{
		if (input[index] == ' ')
			space = index - offset;
		temp += input[index];	
		characters++;
		//osg::notify(osg::NOTICE) << "Characters:  " << characters << std::endl;
	}
	else
	{

		if (temp[index] == ' ')
		{
			temp += "\n ";
			space = index - offset;
			characters = 0;
		}
		else
		{
			temp.erase(space);
			temp += "\n ";
			index = space + offset;
			characters = 0;
		}
	}
	return index;
	
}
/*				*/

